trigger MC_MemberUpdated on Missional_Community_Member__c (after insert, after update)
{
    //If a group member's status changes, do the following
        //If they became a group leader
            //Set the group's group leader name
        //If they became not a group leader
            //If another group leader exists
                //Set the group's group leader name to the first encountered leader
            //If no other group leader exists
                //Set the group's group leader name to empty

    //Create a map of group members who's role has changed and the group they belong to
    Map<Id, Missional_Community_Member__c> updatedMembers=new Map<Id, Missional_Community_Member__c>();
    for(Integer i=0;i<Trigger.new.size();i++)
    {
        if(Trigger.isInsert)    //Inserts are always considered updated
            updatedMembers.put(Trigger.new[i].Missional_Community__c, Trigger.new[i]);
        else if(Trigger.old[i].Role__c!=Trigger.new[i].Role__c)
            updatedMembers.put(Trigger.new[i].Missional_Community__c, Trigger.new[i]);
    }
    
    //Maintain a list of Missional Communities that have changed
    List<Missional_Community__c> updatedGroups=new List<Missional_Community__c>();
    
    //Retrieve the group for every changed group member, along with all other group members in the group
    for(Missional_Community__c mc:
        [select id, Leader_Name__c, (select Contact__r.FirstName, Contact__r.LastName, Role__c from Missional_Community_Members__r)
                from Missional_Community__c where id in :updatedMembers.keySet()])
    {
        Missional_Community_Member__c member=updatedMembers.get(mc.id);
        
        //Begin the actual processing
        if(member.Role__c=='Leader')    //They became a leader
        {
            //Find the leader in the group's member list (Contact is not included in the Trigger.new results)
            for(Missional_Community_Member__c otherLeader:mc.Missional_Community_Members__r)
            {
                if(otherLeader.id==member.id)
                {
                    mc.Leader_Name__c=otherLeader.Contact__r.FirstName+' '+otherLeader.Contact__r.LastName;
                    break;
                }
            }
        }
        else                            //They became not a leader
        {
            //Find any other leaders and pick the first one we find
            Boolean foundALeader=false;
            for(Missional_Community_Member__c otherLeader:mc.Missional_Community_Members__r)
            {
                if(otherLeader.Role__c=='Leader')
                {
                    mc.Leader_Name__c=otherLeader.Contact__r.FirstName+' '+otherLeader.Contact__r.LastName;
                    foundALeader=true;
                    break;
                }
            }
            if(foundALeader==false)
                mc.Leader_Name__c=null;
        }
        updatedGroups.add(mc);
    }
    
    update updatedGroups;
}